from django.utils import timezone
from rest_framework import serializers

from app01 import models
from app01.models import BookInfo


class BookInfoSerializer(serializers.Serializer):
    id = serializers.IntegerField(label='id', read_only=True)
    btitle = serializers.CharField(max_length=20, label='名称')
    bpub_date = serializers.DateTimeField(label='发布日期', default=timezone.now())
    bread = serializers.IntegerField(default=0, label='阅读数量')
    bcomment = serializers.IntegerField(default=0, label='评论量', max_value=999999, min_value=0)
    is_delete = serializers.BooleanField(default=False, label='逻辑删除')
    mobile = serializers.CharField(max_length=11, read_only=True)

    def validate_btitle(self, value):
        # value 就是btitle
        print('value---', value)
        if '金瓶梅' not in value:
            raise serializers.ValidationError('书籍名不合法')
        return value
    # 反向关联外键英雄, 主键 模型类小写_set
    # 一查多，要加many=True
    # heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)

    # 多字段校验 两两对应校验
    def validate(self, attrs: dict):
        # attrs 就是外面传进来的data
        print('attrs', attrs)
        bread = attrs.get('bread')
        bcomment = attrs.get('bcomment')
        if bread > bcomment:
            raise serializers.ValidationError('数据不合法')
        return attrs


class HeroSerializr(serializers.Serializer):
    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'female')
    )

    id = serializers.IntegerField(label='ID', read_only=True)
    hname = serializers.CharField(max_length=20, label='名称')
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, required=False, label='性别')
    hcomment = serializers.CharField(max_length=200, label='描述信息')
    is_delete = serializers.BooleanField(required=False)

    # hbook = serializers.PrimaryKeyRelatedField(read_only=True)
    # hbook = serializers.PrimaryKeyRelatedField(queryset=BookInfo.objects.all())
    # hbook = serializers.StringRelatedField(read_only=True)
    hbook = BookInfoSerializer()


class BookInfoModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BookInfo
        fields = '__all__'

        # extra_kwargs 给生成的字段添加选项约束
        extra_kwargs = {
            "bread": {"max_value": 99999, "min_value": 0},
            "bcomment": {"max_value": 99999, "min_value": 0}
        }

























